<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="科目名称" prop="name">
        <el-input
          style="width:80%"
          v-model="queryParams.name"
          placeholder="请输入考试科目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目类型" prop="type" class="reduce-margin">
        <el-select v-model="queryParams.type" placeholder="请选择科目类型" clearable style="width:80%">
          <el-option
            v-for="dict in dict.type.examination_course_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学校名称" prop="universityName" class="reduce-margin">
        <el-input
          style="width:80%"
          v-model="queryParams.universityName"
          placeholder="请输入学校名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业名称" prop="majorName" class="reduce-margin">
        <el-input
          style="width:80%"
          v-model="queryParams.majorName"
          placeholder="请输入专业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['DataManage:examination_course:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['DataManage:examination_course:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['DataManage:examination_course:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['DataManage:examination_course:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examination_courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="考试科目名称" align="center" prop="name" width="200"/>
      <el-table-column label="科目类型" align="center" prop="type" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.examination_course_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center"
                       prop="universityName"/>
      <el-table-column label="专业"
                       align="center" prop="majorName"/>
      <el-table-column label="科目满分" align="center" prop="score"/>
      <el-table-column label="考试时间" align="center" prop="time" width="260">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['DataManage:examination_course:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['DataManage:examination_course:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试科目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="考试科目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入考试科目名称"/>
        </el-form-item>
        <el-form-item label="考试科目满分" prop="score">
          <el-input v-model="form.score" placeholder="请输入考试科目满分"/>
        </el-form-item>
        <el-form-item label="考试时间" prop="time">
          <el-date-picker clearable
                          v-model="form.time"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择考试时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="科目类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择表示科目类型">
            <el-option
              v-for="dict in dict.type.examination_course_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试学校" prop="universityId">
          <el-select v-model="form.universityId"
                     @change="getUniversityPromotion(form.universityId)"
                     style="width: 80%"
                     placeholder="请选择"
                     :disabled="form.universityId === '无数据'">
            <el-option v-for="item in universityList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId"
                     style="width: 80%"
                     placeholder="请先选择学校，再选择专业">
            <el-option v-for="item in majorList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExamination_course,
  getExamination_course,
  delExamination_course,
  addExamination_course,
  updateExamination_course,
  universityList,
  majorList
} from "@/api/DataManage/examination_course";
import {provinceList} from "@/api/DataManage/university";

export default {
  name: "Examination_course",
  dicts: ['examination_course_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //表示为edit还是add操作
      actionType: '',
      // 总条数
      total: 0,
      // 考试科目管理表格数据
      examination_courseList: [],
      //学校Id
      universityId: '',
      //学校列表
      universityList: [],
      //专业Id
      majorId: '',
      //专业列表
      majorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        universityName: null,
        majorName: null
      },
      // 表单参数
      form: { },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "考试科目名称不能为空", trigger: "blur"}
        ],
        score: [
          {required: true, message: "考试科目满分不能为空", trigger: "blur"}
        ],
        time: [
          {required: true, message: "考试时间不能为空", trigger: "blur"}
        ],
        type: [
          {
            required: true,
            message: "科目类型不能为空",
            trigger: "change"
          }
        ],
      }
    };
  },
  mounted() {
    this.getUniversityList();
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询考试科目管理列表 */
    getList() {
      this.loading = true;
      listExamination_course(this.queryParams).then(response => {
        this.examination_courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        score: null,
        time: null,
        type: null,
        universityId: null,
        majorId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试科目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExamination_course(id).then(response => {
        this.form = response.data;
        // 如果是通识课程，则不进行学校和专业的回显
        if (this.isGeneralCourse()) {
          this.open = true;
          this.form.universityId = '无数据';
          this.form.majorId = '无数据';
        }
        else{
          // 根据学校 ID 获取专业列表，并匹配专业名称
          this.checkUniversityPromotion(this.form.universityId);
        }
        this.title = "修改考试科目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExamination_course(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamination_course(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试科目管理编号为"' + ids + '"的数据项？').then(function () {
        return delExamination_course(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('DataManage/examination_course/export', {
        ...this.queryParams
      }, `examination_course_${new Date().getTime()}.xlsx`)
    },
    //获取学校下拉数据
    getUniversityList() {
      this.loading = true;
      universityList()
        .then(res => {
          this.universityList = res.data.map(item => {
            return {value: item.id, label: item.name};
          });
        }).catch(() => {
        // 处理错误
      });
    },
    //获取专业下拉数据
    checkUniversityPromotion(universityId) {
      this.open = false; // 隐藏修改弹窗
      majorList(universityId).then(res => {
        this.majorList = res.data.map(item => {
          return {value: item.id, label: item.name};
        });
        // 匹配专业名称
        const selectedMajor = this.majorList.find(major => major.value === this.form.majorId);
        if (selectedMajor) {
          this.form.majorName = selectedMajor.label;
        }
        this.open = true; // 显示修改弹窗
      });
    },
    getUniversityPromotion(universityId) {
      // 清空当前选中的专业ID
      this.form.majorId = null;
      // 清空专业列表
      this.majorList = [];
      // 重置专业名称字段
      this.form.majorName = '';
      majorList(universityId).then(res => {
        this.majorList = res.data.map(item => {
          return {value: item.id, label: item.name};
        });
        // 匹配专业名称
        const selectedMajor = this.majorList.find(major => major.value === this.form.majorId);
        if (selectedMajor) {
          this.form.majorName = selectedMajor.label;
        }
      });
    },
    isGeneralCourse() {
      return this.form.universityId === 0 && this.form.majorId === 0;
    }

  }
};
</script>
<style>
.reduce-margin {
  margin-left: -40px; /* 负值用来向左移动 */
}
</style>
